#include "Filtering.h"

/**
 * 一阶滞后滤波函数
 * @param current_voltage 当前采样电压值 (0-24V)
 * @param last_voltage 上次滤波后的电压值 (0-24V)
 * @param alpha 滤波系数 (0.0-1.0)，值越小滤波效果越强
 * @return 滤波后的电压值 (0-24V)
 */
float voltage_filter(float current_voltage, float last_voltage, float alpha)
{
    // 参数有效性检查
    if (current_voltage < 0.0f) current_voltage = 0.0f;
    if (current_voltage > 24.0f) current_voltage = 24.0f;
    if (last_voltage < 0.0f) last_voltage = 0.0f;
    if (last_voltage > 24.0f) last_voltage = 24.0f;
    if (alpha < 0.0f) alpha = 0.0f;
    if (alpha > 1.0f) alpha = 1.0f;
    
    // 一阶滞后滤波公式：本次滤波结果 = α × 本次采样值 + (1-α) × 上次滤波结果
    float filtered_voltage = alpha * current_voltage + (1.0f - alpha) * last_voltage;
    
    // 确保输出在有效范围内
    if (filtered_voltage < 0.0f) filtered_voltage = 0.0f;
    if (filtered_voltage > 24.0f) filtered_voltage = 24.0f;
    
    return filtered_voltage;
}
